package controller

import (
	"codeGenerator/service"
	jsoniter "github.com/json-iterator/go"
	"github.com/savsgio/atreugo/v11"
	"path"
)

type CodeAutoCtl struct {
	CodeAutoSrv *service.CodeAutoSrv
}

func NewCodeAutoCtl() *CodeAutoCtl {
	return &CodeAutoCtl{
		CodeAutoSrv: service.NewCodeAutoSrv(),
	}
}

func (cat *CodeAutoCtl) Generator(ctx *atreugo.RequestCtx) error {
	codeInfoList := new([]map[string]interface{})

	err := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(ctx.PostBody(), codeInfoList)
	if err != nil {
		return ctx.JSONResponse(map[string]interface{}{
			"code":    500,
			"message": err.Error(),
			"data":    nil},
		)
	}

	return ctx.JSONResponse(map[string]interface{}{
		"code":    "200",
		"data":    cat.CodeAutoSrv.Generator(*codeInfoList),
		"message": "成功",
	})
}

func (cat *CodeAutoCtl) Download(ctx *atreugo.RequestCtx) error {
	projectName := string(ctx.FormValue("projectName"))

	cat.CodeAutoSrv.Zip(projectName)

	filePath := "D:/test/" + projectName + ".zip"

	//获取文件的名称
	fileName := path.Base(filePath)

	ctx.SetContentType("aContent-Disposition")
	//强制浏览器下载
	ctx.Response.Header.Set("Content-Disposition", "attachment; filename="+fileName)
	//浏览器下载或预览
	ctx.Response.Header.Set("Content-Disposition", "inline;filename="+fileName)
	ctx.Response.Header.Set("Content-Transfer-Encoding", "binary")
	ctx.Response.Header.Set("Cache-Control", "no-cache")

	ctx.SendFile(filePath)

	return nil
}
